//
//  SISSHouseCooperationProgressViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/7/3.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSHouseCooperationProgressViewController.h"
#import "SISSMorePopupView.h"
#import "SISSProgressCell.h"
#import "SISSProgressBottomView.h"
#import "SISSHouseCooperationDetailViewController.h"
#import "SISSNetworkingManager+Home.h"
#import "SISSNetworkingManager+CoopProgress.h"
#import "SISSChatViewController.h"
#import "SISSUploadCooperationContractViewController.h"
#import "SISSCooperationContractShowViewController.h"
#import "SISSAddTakeLookViewController.h"
#import "SISSHouseCoopTakeLookRecordViewController.h"
#import "SISSAddCoopCommentViewController.h"
#import "SISSCoopCommentListViewController.h"
//#import "SISSCooperationUploadContractsViewController.h"
//#import "SISSVerticalShowImageViewController.h"
#import "SISSHistoryProgressCell.h"
#import "SISSNetworkingManager+Mine.h"
#import "SISSInfomationViewController.h"
#import "SISSCoopContractShowViewController.h"
#import "SISSUploadCoopContractViewController.h"

static NSString *houseCoopProgressCellReuseID = @"houseCoopProgressCellReuseID";
static NSString *houseCoopHistoryProgressCellReuseID = @"houseCoopHistoryProgressCellReuseID";
@interface SISSHouseCooperationProgressViewController ()<UITableViewDelegate,UITableViewDataSource,SISSMorePopupViewDelegate,SISSProgressBottomViewDelegate>

/* tableView */
@property (weak, nonatomic) SISSBaseTableView *tableView;
/* bottomView */
@property (weak, nonatomic) SISSProgressBottomView *bottomView;

/* 数据 */
@property (copy, nonatomic) NSArray *dataArr;
/* 房源进度信息模型 */
@property (strong, nonatomic) SISSHouseCoopProgressInfoModel *coopProgressInfoModel;
/* 房源合作进度合作协议模型 */
@property (strong, nonatomic) SISSCooperationAgreementModel *agreementModel;

@end

@implementation SISSHouseCooperationProgressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WeakSelf
    [kSISSRefresh prepareHeaderRefresh:self.tableView loadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeUpDown;
        [weakSelf requestHouseCooperationProgressRecordInfo];
    }];
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // 获取合作记录时间和id信息
    [self requestHouseCooperationProgressRecordInfo];
}

- (void)setHouseCoopProgressModel:(SISSHouseCoopProgressModel *)houseCoopProgressModel {
    _houseCoopProgressModel = houseCoopProgressModel;
    self.bottomView.iconUrlStr = houseCoopProgressModel.portrait;
    self.bottomView.name = houseCoopProgressModel.name;
}

#pragma mark - 代理
#pragma mark -- UITableViewDelegate & UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    if (self.isHistory) {
//        SISSHistoryProgressCell *cell = [tableView dequeueReusableCellWithIdentifier:houseCoopHistoryProgressCellReuseID forIndexPath:indexPath];
//        cell.rowCount = self.dataArr.count - 1;
//        // 优化从外面点击进入的体验
//        cell.progress = self.coopProgressInfoModel ? self.coopProgressInfoModel.progress : self.houseCoopProgressModel.progress;
//        cell.index = indexPath.row;
//        cell.title = self.dataArr[indexPath.row];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        // 判断cell能否点击跳转
//        cell.userInteractionEnabled = indexPath.row <= self.coopProgressInfoModel.progress;
//        cell.timeStr = [self getTimeStrWithIndex:indexPath.row];
//        return cell;
//
//    } else
    {
        
        SISSProgressCell *cell = [tableView dequeueReusableCellWithIdentifier:houseCoopProgressCellReuseID forIndexPath:indexPath];
        
        // 优化从外面点击进入的体验
        NSInteger progress = self.coopProgressInfoModel ? self.coopProgressInfoModel.progress : self.houseCoopProgressModel.progress;
        cell.isFisrtCell = indexPath.row == 0;
        cell.isLastCell = indexPath.row == self.dataArr.count - 1;
        if (progress > indexPath.row) {
            cell.progressStatus = 1;
            cell.topIsDash = NO;
            cell.bottomIsDash = NO;
            cell.userInteractionEnabled = YES;
        } else if (progress == indexPath.row) {
            cell.topIsDash = NO;
            cell.progressStatus = self.isHistory ? 3 : 2;
            cell.bottomIsDash = YES;
            cell.userInteractionEnabled = self.coopProgressInfoModel.progress == 5 ? YES : !self.isHistory;
        } else {
            cell.progressStatus = 3;
            cell.topIsDash = YES;
            cell.bottomIsDash = YES;
            cell.userInteractionEnabled = NO;
        }
        cell.title = self.dataArr[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        // 判断cell能否点击跳转
//        cell.userInteractionEnabled = indexPath.row <= self.coopProgressInfoModel.progress;
        cell.timeStr = [self getTimeStrWithIndex:indexPath.row];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 88;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    if (indexPath.row > self.houseCoopProgressModel.progress) return;
    
    switch (indexPath.row) {
        case 0: {
            NSDictionary *parameters = @{
                                         @"ahcrId":self.coopProgressInfoModel.ID
                                         };
            [kNetworkManager requestHouseCooperationDetailWithparameters:parameters success:^(SISSHouseCooperationDetailModel *houseCooperationModel) {
                
                SISSHouseCooperationDetailViewController *vc = [[SISSHouseCooperationDetailViewController alloc] init];
                vc.isFindCooperation = YES;
                vc.isHideConsultAndRequestView = YES;
                vc.title = @"房源合作详情";
                vc.houseCooperationModel = houseCooperationModel;
                [self.navigationController pushViewController:vc animated:YES];
                
            } failed:^(NSError *error) {
                
                NSLog(@"%@",error);
            }];

        }
            break;
        case 1: {

            if (self.coopProgressInfoModel.hasCooperationcontract == 1) {
                SISSCooperationContractShowViewController *vc = [[SISSCooperationContractShowViewController alloc] init];
                vc.abpId = self.houseCoopProgressModel.ID;
                vc.isHouseCooperatonIn = YES;
                [self.navigationController pushViewController:vc animated:YES];
            } else { 
                SISSUploadCooperationContractViewController *vc = [[SISSUploadCooperationContractViewController alloc] init];
                vc.abpId = self.houseCoopProgressModel.ID;
                vc.isHouseCooperatonIn = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
        case 2: {
            
            SISSHouseCoopTakeLookRecordViewController *vc = [[SISSHouseCoopTakeLookRecordViewController alloc] init];
            vc.type = self.houseCoopProgressModel.type;
            vc.isHistory = self.isHistory;
            vc.houseCoopProgressModel = self.houseCoopProgressModel;
            [self.navigationController pushViewController:vc animated:YES];
            
        }
            break;
        case 3: {
            if (self.coopProgressInfoModel.hasMiddlecontract == 1) {

                SISSCoopContractShowViewController *vc = [[SISSCoopContractShowViewController alloc] init];
                vc.contractType = 1;
                vc.isHouseCooperatonIn = YES;
                vc.abpId = self.houseCoopProgressModel.ID;
                vc.isHistory = self.isHistory;
                vc.title = @"居间服务合同详情";
                [self.navigationController pushViewController:vc animated:YES];
            } else {
                SISSUploadCoopContractViewController *vc = [[SISSUploadCoopContractViewController alloc] init];
                vc.contractType = 1;
                vc.isHouseCooperatonIn = YES;
                vc.abpId = self.houseCoopProgressModel.ID;
                vc.title = @"居间服务合同";
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
        case 4: {
            if (self.coopProgressInfoModel.hasBusinesscontract == 1) {
                SISSCoopContractShowViewController *vc = [[SISSCoopContractShowViewController alloc] init];
                vc.contractType = 2;
                vc.isHouseCooperatonIn = YES;
                vc.abpId = self.houseCoopProgressModel.ID;
                vc.isHistory = self.isHistory;
                vc.title = @"二手房买卖合同详情";
                [self.navigationController pushViewController:vc animated:YES];
            } else {
                SISSUploadCoopContractViewController *vc = [[SISSUploadCoopContractViewController alloc] init];
                vc.contractType = 2;
                vc.isHouseCooperatonIn = YES;
                vc.abpId = self.houseCoopProgressModel.ID;
                vc.title = @"二手房买卖合同";
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
        case 5: {
            SISSCoopCommentListViewController *vc = [[SISSCoopCommentListViewController alloc] init];
            vc.houseCoopProgressModel = self.houseCoopProgressModel;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;

            
        default:
            break;
    }
}

#pragma mark -- SISSMorePopupViewDelegate 删除 举报
- (void)morePopupViewSelectedWithIndex:(NSInteger)index {
    
    if (self.coopProgressInfoModel.progress > 1) { // 举报
        [self reportHouse];
    } else {
        if (index == 0) { // 删除
            NSString *str = @"删除后不可恢复，您确定删除吗？";
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            paragraphStyle.alignment = NSTextAlignmentLeft;
            
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13], NSForegroundColorAttributeName: COLOR(0x334A60), NSParagraphStyleAttributeName: paragraphStyle}];
            
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"删除" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            [alertC setValue:attr forKey:@"attributedMessage"];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"取消");
            }];
            
            [alertC addAction:cancelAction];
            
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"确定");
                
                [self deleteHouseCooperationProgress];
            }];
            [alertC addAction:okAction];
            
            [self presentViewController:alertC animated:YES completion:nil];
        } else { // 举报
            [self reportHouse];
        }
    }
}

#pragma mark -- SISSProgressBottomViewDelegate 头像、电话、在线咨询
- (void)clickBottomButtonWithIndex:(NSInteger)index {
    
    if (index == 0) { // 点击头像或名字的
        NSLog(@"人员信息");
        [kNetworkManager requestPersonInfoWithSpId:self.houseCoopProgressModel.sp_id success:^(SISSPersonInfoModel *personInfo) {
            
            SISSInfomationViewController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"SISSInfomationViewController"];
            vc.personInfo = personInfo;
            
            vc.spId = self.houseCoopProgressModel.sp_id;
            [self.navigationController pushViewController:vc animated:YES];
            
        } failed:^(NSError *error) {
            
            NSLog(@"%@",error);
        }];

    } else if (index == 1) { // 点击拨打电话
        
        UIWebView *callWebview = [[UIWebView alloc] init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",self.houseCoopProgressModel.mobile]]]];
        [self.view addSubview:callWebview];
        
    } else { // 点击联系人
        
        SISSChatViewController *chatVC = [[SISSChatViewController alloc] initWithConversationChatter:self.houseCoopProgressModel.imAccount conversationType:EMConversationTypeChat];
        SISSContactModel *model = [[SISSContactModel alloc] init];
        model.name = self.houseCoopProgressModel.name;
        model.portrait = self.houseCoopProgressModel.portrait;
        model.spId = self.houseCoopProgressModel.sp_id;
        model.accountType = 1;
        chatVC.contactModel = model;
        chatVC.title = self.houseCoopProgressModel.name;
        [self.navigationController pushViewController:chatVC animated:YES];
    }
}
#pragma mark - 点击事件
#pragma mark -- 右上角更多按钮点击事件
- (void)rightMoreItemClickAction {
    NSArray *titleArr =  self.coopProgressInfoModel.progress > 1 ? @[@"举报"] : @[@"删除", @"举报"];
    SISSMorePopupView *moreView = [[SISSMorePopupView alloc] initWithTitles:titleArr];
    moreView.delegate = self;
    [moreView show];
}

#pragma mark - 加载数据
#pragma mark -- 获取合作记录时间和id信息
- (void)requestHouseCooperationProgressRecordInfo {
    
    WeakSelf
    [kNetworkManager requestHouseCooperationProgressRecordInfoWithAhbId:self.houseCoopProgressModel.ID success:^(SISSHouseCoopProgressInfoModel *progressInfoModel) {
        
        weakSelf.coopProgressInfoModel = progressInfoModel;
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView reloadData];
        }];
        
    } failed:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        NSLog(@"%@",error);
    }];
}

#pragma mark -- 删除请求
- (void)deleteHouseCooperationProgress {
    [kNetworkManager deleteHouseCooperationProgressWithHouseAhcbId:self.houseCoopProgressModel.ID successBlock:^(id) {
        
        if (self.deleteCompletedBlock) {
            self.deleteCompletedBlock();
        }
        [self.navigationController popViewControllerAnimated:YES];
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
}

/**
 举报
 */
- (void)reportHouse {
    
    SISSReportViewController *vc = [[SISSReportViewController alloc] init];
    SISSHouseResourceModel *houseModel = [[SISSHouseResourceModel alloc] init];
    houseModel.houseresType = self.coopProgressInfoModel.cooperationType;
    houseModel.ID = self.houseCoopProgressModel.ahrId;
    vc.houseModel = houseModel;
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 根据indexPath获取对应的时间字符串
 
 @param index index
 @return 返回对应的时间字符串
 */
- (NSString *)getTimeStrWithIndex:(NSInteger)index {
    
    NSString *timeStr;
    switch (index) {
        case 0:
            timeStr = [NSDate yyr_stringToString:self.coopProgressInfoModel.insertTime];
            break;
        case 1:
//            timeStr = [self getFinalSignAgreementTime];
            break;
        case 2:
            timeStr = [NSDate yyr_stringToString:self.coopProgressInfoModel.takelookTime];
            break;
        case 3:
            timeStr = [NSDate yyr_stringToString:self.coopProgressInfoModel.uploadContractTime];
            break;
        case 4:
            timeStr = [NSDate yyr_stringToString:self.coopProgressInfoModel.uploadBusinessContractTime];
            break;
        case 5:
            timeStr = [NSDate yyr_stringToString:self.coopProgressInfoModel.serviceCommentTime];
            break;
            
        default:
            break;
    }
    return timeStr;
}


#pragma mark - navigationItem
- (void)setupNavigationItems {
    [super setupNavigationItems];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"more..."] style:UIBarButtonItemStylePlain target:self action:@selector(rightMoreItemClickAction)];
}


#pragma mark - UI
- (void)setupSubviews {
    [super setupSubviews];
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] init];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerClass:[SISSProgressCell class] forCellReuseIdentifier:houseCoopProgressCellReuseID];
    [tableView registerClass:[SISSHistoryProgressCell class] forCellReuseIdentifier:houseCoopHistoryProgressCellReuseID];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    SISSProgressBottomView *bottomView = [[SISSProgressBottomView alloc] init];
    bottomView.delegate = self;
    bottomView.iconUrlStr = self.houseCoopProgressModel.portrait;
    bottomView.name = self.houseCoopProgressModel.name;
    bottomView.hidden = self.isHistory;
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    
    // 自动布局
    WeakSelf
    CGFloat bottomViewHeight = 44.0;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(weakSelf.view);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_equalTo(bottomViewHeight);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(weakSelf.view);
        }
    }];
}

#pragma mark - 懒加载
- (NSArray *)dataArr {
    if (!_dataArr) {
        
        NSArray *arr = @[
                         @"发布房源合作信息",
                         @"上传已签署的《二手房交易合作协议》",
                         @"合作方带客户看房并添加看房客户",
                         @"上传已签署的《居间服务合同》",
                         @"上传网签后的《二手房买卖合同》",
                         @"服务评价"
                         ];
        _dataArr = arr;
    }
    return _dataArr;
}



@end
